package com.ticket.sass.common.wxpay;

/**
 * @author ywb
 * @date 2024-05-22 16:45
 */

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import org.apache.http.ssl.SSLContexts;

import javax.net.ssl.SSLContext;
import java.io.ByteArrayInputStream;
import java.security.KeyStore;
import java.util.Base64;

public class WxPayConfigManager {
    
    public static WxPayService buildWxPayService(String appId, String mchId, String mchKey, String p12Content) throws Exception {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(appId);
        payConfig.setMchId(mchId);
        payConfig.setMchKey(mchKey);
        
        // 解析 P12 内容
        byte[] p12Bytes = Base64.getDecoder().decode(p12Content);
        SSLContext sslContext = generateSSLContextFromP12(p12Bytes, mchId);
        payConfig.setSslContext(sslContext);
        
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }
    
    private static SSLContext generateSSLContextFromP12(byte[] p12Bytes, String mchId) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(new ByteArrayInputStream(p12Bytes), mchId.toCharArray());
        
        return SSLContexts.custom().loadKeyMaterial(keyStore, mchId.toCharArray()).build();
    }
}

